package com.rritw.webtools.action.tool;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;

import com.googlecode.htmlcompressor.compressor.HtmlCompressor;
import com.rritw.webtools.action.IpsAction;
import com.rritw.webtools.util.JSUtil;
import com.rritw.webtools.util.StringUtil;

@Controller
@Scope("prototype")
public class JavaScriptCompressAction extends IpsAction {

    private static final long   serialVersionUID = -6919152621248050853L;
    private static final Logger log              = Logger.getLogger(JavaScriptCompressAction.class);
    private String              content;
    private String              contentResult;

    public String index() {
        super.init();
        return SUCCESS;
    }

    public String create() {
        super.init();
        if (StringUtil.isEmpty(content)) {
            log.warn("Content is empty.");
            return ERROR;
        }
        try {
            HtmlCompressor compressor = new HtmlCompressor();
            compressor.setCompressCss(true); // compress inline css
            compressor.setCompressJavaScript(true); // compress inline javascript
            compressor.setYuiCssLineBreak(-1); // --line-break param for Yahoo YUI Compressor
            compressor.setYuiJsDisableOptimizations(false); // --disable-optimizations param for Yahoo YUI Compressor
            compressor.setYuiJsLineBreak(-1); // --line-break param for Yahoo YUI Compressor
            compressor.setYuiJsNoMunge(true); // --nomunge param for Yahoo YUI Compressor
            compressor.setYuiJsPreserveAllSemiColons(true);// --preserve-semi param for Yahoo YUI Compressor
            compressor.setRemoveComments(true);// Remove comments
            contentResult = compressor.compress(JSUtil.removeJSComments(content));
            if (!StringUtil.isEmpty(content)) {
                content = HtmlUtils.htmlEscape(content);
            }
            if (!StringUtil.isEmpty(contentResult)) {
                contentResult = HtmlUtils.htmlEscape(contentResult);
            }
            return SUCCESS;
        } catch (Exception e) {
            log.error("Compress Javascript exception happened:" + e.getMessage(), e);
            return ERROR;
        }
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getContentResult() {
        return contentResult;
    }

}
